package com.panshi.controller.qiniu;

import com.panshi.qiniuyun.QiniuUtils;
import com.panshi.qiniuyun.UploadImageImp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class QiNiuController {

    @Resource
    private UploadImageImp uploadImageImp;

    @PostMapping("/zx/upload")
    @ResponseBody
    public Map<String , Object> uploadImg(@RequestParam("editorPic") MultipartFile myPic) throws IOException {

        Map<String , Object> map = new  HashMap<>();

        //获取文件的名称
        String fileName = myPic.getOriginalFilename();

        //使用工具类根据上传文件生成唯一的图片名称
        String imgName = QiniuUtils.getRandomImgName(fileName);

        if(!myPic.isEmpty()){

            FileInputStream stream = (FileInputStream) myPic.getInputStream();

            String path = uploadImageImp.uploadQNImg(stream,imgName);

            path = "http://"+path;

            log.info("七牛云返回的图片链接*****************：{}",path);

            map.put("success",true);
            map.put("file_path",path);

            return map;
        }
        map.put("success",false);
        return map;
    }

}
